<?php
/**
 * Joomla! 1.5 component ArticleCashRewards
 *
 * @version $Id: adhoc.php 2009-05-10 01:47:01 svn $
 * @author Maverick
 * @package models
 * @subpackage ArticleCashRewards
 * @license GNU/GPL
 * Website: http://www.boddunan.com
 *
 * Review and approve the articles and assign points and cash rewards.
 * Users can see their articles and the points/cash rewards assigned in the front-end module.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

if(!class_exists('ContentHelperRoute')) require_once (JPATH_SITE . '/components/com_content/helpers/route.php');  

class ArticleCashRewardsModelAwards extends JModel {

	var $_total = null; 
	var $_pagination = null;
	
	function __construct(){
	
		parent::__construct();
		global $mainframe, $option;
	
		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest($option.'.limitstart', 'limitstart', 0, 'int');

		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

    function getAdhocPaymentsMade() {
	    
    	global $mainframe, $option;
    	
    	// Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
		$filter_order		= $mainframe->getUserStateFromRequest( "$option.filter_order",		'filter_order',		'u.name',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( "$option.filter_order_Dir",	'filter_order_Dir',	'DESC',		'word' );
		
		$orderby 	= ' ORDER BY a.pay_date DESC';

		$query = 'SELECT a.id as id, a.amount, t.description as type, a.description as description,'.
            ' u.name as author, a.description, a.pay_date, a.admin_uid as admin_uid FROM ' .
            TABLE_ACR_ADHOC . ' a LEFT JOIN ' . TABLE_ACR_ADHOC_TYPES . ' t ON a.type=t.id'.
            ' LEFT JOIN #__users u ON a.author=u.id'.$orderby;
//echo $query;

		$db->setQuery($query, $this->getState('limitstart'), $this->getState('limit'));
		$rows = $db->loadObjectList();

		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;
		
		$result->rows = $rows;
		$result->lists = $lists;
		
		return $result;
    }

    function getAdhocPaymentMade(){

        $db =& JFactory::getDBO();

        $payid = JRequest::getVar( 'payid', null);
        $selected = null;

        if(isset($payid)){
            $query = 'SELECT id, amount, type, author, description, pay_date FROM ' .
                TABLE_ACR_ADHOC . ' WHERE id='.$payid;
            $db->setQuery($query);
            $selected = $db->loadAssoc();
        }

        return $selected;
    }

    function getAdhocPaymentTypes($all){
        
        $db =& JFactory::getDBO();

		$query = 'SELECT * FROM ' . TABLE_ACR_ADHOC_TYPES;
        if(!$all){
            $query .= ' WHERE status IN (1)';
        }else{
            $query .= ' WHERE status IN (0,1)';
        }
        $db->setQuery($query);
		$rows = $db->loadObjectList();

        $result->rows = $rows;
        $result->selected = $this->getAdhocPamentType();
        
        return $result;
    }

    function getAdhocPamentType(){

        $db =& JFactory::getDBO();
        $adhoc_type_selected = JRequest::getVar( 'tselected', null);

        $selected = null;
        if(isset($adhoc_type_selected)){
            $query = 'SELECT * FROM ' . TABLE_ACR_ADHOC_TYPES . ' WHERE id='.$adhoc_type_selected;
            $db->setQuery($query);
            $selected = $db->loadAssoc();
        }
        return $selected;
    }

    function saveType(){
		$db =& JFactory::getDBO();
        $adhoc_type = JRequest::getVar( 'adhoc_type', null);
        $desc = JRequest::getVar( 'description', null);

        if(!isset($adhoc_type)){
            $query = 'INSERT INTO ' . TABLE_ACR_ADHOC_TYPES . '(description) VALUES ("'. $desc . '")';
        }else{
            $query = 'UPDATE ' . TABLE_ACR_ADHOC_TYPES . ' SET description="'.$desc . '" WHERE id=' . $adhoc_type;
        }

        $db->setQuery($query);
        if(!$db->query()){
            $this->setError($this->_db->getErrorMsg());
            return false;
        }else{
            return true;
        }
    }

    function save(){
		$db             =& JFactory::getDBO();
		$user           =& JFactory::getUser();
        $payment_id     = JRequest::getVar( 'payment_id', null, 'post', 'INTEGER');
        $amount         = JRequest::getVar( 'amount', null, 'post', 'FLOAT');
        $description    = JRequest::getVar( 'description', null, 'post', 'STRING');
        $author_id      = JRequest::getVar( 'author_ids', null, 'post', 'INTEGER');
        $adhoc_type     = JRequest::getVar( 'adhoc_type', null, 'post', 'INTEGER');

        $author_ids = explode(',',$author_id);

        if($payment_id != null){
            $query = 'UPDATE ' . TABLE_ACR_ADHOC . ' SET amount=' . $amount . ',' .
                ' description="' . $description . '", author=' . $author_id .
                ' ,pay_date=NOW(), admin_uid=' . $user->id . ', type=' . $adhoc_type .
                ' WHERE' . ' id=' . $payment_id;
        }else{
            $query = 'INSERT INTO '. TABLE_ACR_ADHOC . '(amount,type,description,'.
                'author,pay_date,admin_uid, status) VALUES ';
            $i=0;
            foreach($author_ids as $author){
                if($i > 0){
                    $query .= ',';
                }
                $query .= '(' . $amount . ',' . $adhoc_type . ',"' . $description .
                    '",' . $author . ',NOW(),' . $user->id . ', ' . STATUS_APPROVED . ')';
                $i += 1;
            }
        }
        $db->setQuery($query);
        if(!$db->query()){
            JError::raiseError( 500, $db->getErrorMsg() );
			return false;
        }
        return true;
    }
    
    function getUsers($keyword){
		$db =& JFactory::getDBO();
        $query = 'SELECT id, username, name FROM #__users where name LIKE "%' .
            $keyword . '%" OR username LIKE "%' . $keyword . '%"';
        $db->setQuery($query);
		$rows = $db->loadObjectList();
        return $rows;
    }

    function stateChange($state=0){
		$db =& JFactory::getDBO();

        $cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count($cid) < 1) {
            JError::raiseError( 500, 'No rows selected???' );
			return false;
        }
		$total	= count($cid);
		$cids	= implode(',', $cid);

        $query = 'UPDATE ' . TABLE_ACR_ADHOC_TYPES . ' SET status=' . $state .
            ' WHERE id IN (' . $cids . ')';
        
        $db->setQuery($query);
        if(!$db->query()){
            JError::raiseError( 500, $db->getErrorMsg() );
			return false;
        }
        return $total;
    }

    function getTotal(){

	    if (empty($this->_total)) {
	    
			$db =& JFactory::getDBO();

			$query = 'SELECT COUNT(*) FROM ' . TABLE_ACR_ADHOC;
			$db->setQuery( $query );
			$total = $db->loadResult();
		}			
		return $total;
	}
	  
	function getPagination(){
		$pnls = JRequest::getVar( 'pnlimitstart', 'null');
		
		if($pnls == 'null'){
		    jimport('joomla.html.pagination');
		    $this->_pagination = new JPagination($this->getTotal(), 0, $this->getState('limit') );			
		    $this->setState('limitstart', 0);
		}

		// Load the content if it doesn't already exist
		if (empty($this->_pagination)) {
		    jimport('joomla.html.pagination');
		    $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}    

}
?>